/*
 * @Author: zxh
 * @Email: 1271027008@qq.com
 * @Date: 2020-02-24 08:53:27
 * @Descripttion: 仓库管理
 */
import { Component, OnInit } from '@angular/core';
import { SubwarehouseManageService } from './subwarehouse-manage.service';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalService } from 'ng-zorro-antd/modal';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { id_ID } from 'ng-zorro-antd';
import { HCommonService } from 'src/app/h-common/h-common.service';

@Component({
  selector: 'app-subwarehouse-manage',
  templateUrl: './subwarehouse-manage.component.html',
  styleUrls: ['./subwarehouse-manage.component.scss']
})
export class SubwarehouseManageComponent implements OnInit {

  power:any
  modalDomBoxA : any
  modalDomBoxB : any

  constructor(
    private subwarehouseManageService: SubwarehouseManageService,
    private message: NzMessageService,
    private modalService: NzModalService,
    private KFForm: FormBuilder,
    private KQForm: FormBuilder,
    private HCommonService:HCommonService
  ) { }

  ngOnInit(): void {
    this.modalDomBoxA = document.querySelector("#modal_box_1");
    this.modalDomBoxB = document.querySelector("#modal_box_2");
    /* 获取权限 */
    this.power = this.HCommonService.getRoles("warehouse");
    console.log( this.power );

    this.getKFList()
    this.getClList()
    this.getkfList()
    this.getkqTypeList()
    this.getkqqyList()

    this.KfForm = this.KFForm.group({
      kfCodeModal: ['', [Validators.required]],
      kfNameModal: ['', [Validators.required]],
      kfAddrModal: [''],
      isIndependent: [false],
      kfTypeModal: ['', [Validators.required]],
      clTypeModal: ['', [Validators.required]]
    })
    this.kqForm = this.KQForm.group({
      kqCodeModal: ['', [Validators.required]],
      // pmCodeModal: ['', [Validators.required]],
      pmCodeModal: [''],
      lcCodeModal: [''],
      kqNameModal: ['', [Validators.required]],
      kqDescModal: [''],
      kqTypeModal: [''],
      qyModal: ['']
    })

  }

  kfCode: string = '';//库房编码
  kfName: string = '';//库房名称
  clType: string = '';//存料类型
  pageSize: string = '10'
  clList = []
  kfList = []
  kqTypeList = []
  kqqyList = []
  // 获取存料类型下拉菜单列表
  getClList() {
    let data = {
      dictName:'material_category'
    }
    this.subwarehouseManageService.getclTypeList(data).subscribe(res=>{
      this.clList = res
    })
  }
  // 获取库房类型下拉菜单列表
  async getkfList() {
    let data = {
      dictName:'warehouse_type'
    }
    this.subwarehouseManageService.getclTypeList(data).subscribe(res=>{
      this.kfList = res
    })
  }
  // 获取库区类型下拉菜单列表
  async getkqTypeList() {
    let data = {
      dictName:'warehouse_area_type'
    }
    this.subwarehouseManageService.getclTypeList(data).subscribe(res=>{
      this.kqTypeList = res
    })
  }
  // 获取库区区域下拉菜单列表
  async getkqqyList() {
    let data = {
      dictName:'warehouse_area'
    }
    this.subwarehouseManageService.getclTypeList(data).subscribe(res=>{
      this.kqqyList = res
    })
  }
  //选择存料类型
  selectedCL(data) {
    this.clType = data
    this.getKFList('search')
  }
  // search
  // searchList() {
  //   this.currentKF = '1'
  //   this.pageIndexKF = '0'
  //   this.listOfAllDataDetail = []
  //   this.selectedKQ = ''
  //   this.getKFList()
  // }
  // table1 start
  isAllDisplayDataChecked = false;
  isOperating = false;
  isIndeterminate = false;
  totalSizeKF: any = '';
  currentKF: number = 1;
  listOfDisplayData = [];
  listOfAllData = [];
  mapOfCheckedId: { [key: string]: boolean } = {};
  numberOfChecked = 0;
  deleteKFList = [];
  selectedKQ: string = '';

  currentPageDataChange($event): void {
    this.listOfDisplayData = $event;
    this.refreshStatus();
  }

  refreshStatus(): void {
    this.isAllDisplayDataChecked = this.listOfDisplayData
      .filter(item => !item.disabled)
      .every(item => this.mapOfCheckedId[item.id]);
      if(this.listOfDisplayData.length==0){
        this.isAllDisplayDataChecked = false
      }
    this.isIndeterminate =
      this.listOfDisplayData.filter(item => !item.disabled).some(item => this.mapOfCheckedId[item.id]) &&
      !this.isAllDisplayDataChecked;
    this.numberOfChecked = this.listOfAllData.filter(item => this.mapOfCheckedId[item.id]).length;

    // 删除库房id
    let newList = []
    let ids = Object.keys(this.mapOfCheckedId)
    for (let i = 0; i < ids.length; i++) {
      if (this.mapOfCheckedId[ids[i]]) {
        newList.push(ids[i])
      }
    }
    this.deleteKFList = newList
  }

  checkAll(value: boolean): void {
    this.listOfDisplayData.filter(item => !item.disabled).forEach(item => (this.mapOfCheckedId[item.id] = value));
    this.refreshStatus();
  }

  // 获取库房列表
  async getKFList(type?) {
    if(type){
      this.isEditKQ = false
      this.listOfAllDataDetail = []
      this.selectedKQ = ''
      if(type=='search'){
        this.currentKF = 1
      }
    }
    let data = {
      code: this.kfCode,
      name: this.kfName,
      materialCategory: this.clType == null ? '' : this.clType,
      page: this.currentKF - 1,
      size: this.pageSize
    }
    let list: any = await this.subwarehouseManageService.getKFList(data)
    this.listOfAllData = list.content
    this.totalSizeKF = list.totalElements
    this.isCanAddEdit = true
    if (this.isEditKQ) {
      this.getKQList()
      this.isCanAddEdit = false
    }
  }

  // 点击页码
  clickPageKF(pageIndex) {
    this.currentKF = pageIndex
    this.listOfAllDataDetail = []
    this.selectedKQ = ''
    this.getKFList()
  }
  // 删除库房
  geleteCurkf(id: any) {
    let that = this
    this.modalService.confirm({
      nzTitle: '确定要删除此条数据吗？',
      nzContent: '',
      nzOkText: '确认',
      nzCancelText: '取消',
      nzOnOk: async function () {
        that.deleteKFList.push(id)
        let _res1: any = await that.subwarehouseManageService.deletekf(that.deleteKFList)
        that.deleteKFList = []
        that.getKFList('delete')
      },
      nzOnCancel: function () {
        that.deleteKFList = []
      }
    });
  }
  deleteMorekf() {
    let that = this
    if (this.deleteKFList.length == 0) {
      this.message.create("error", "请选择删除条目")
    } else {
      this.modalService.confirm({
        nzTitle: '确定要删除这些数据吗？',
        nzContent: '',
        nzOkText: '确认',
        nzCancelText: '取消',
        nzOnOk: async function () {
          let _res2: any = await that.subwarehouseManageService.deletekf(that.deleteKFList)
          that.deleteKFList = []
          that.mapOfCheckedId = {}
          if(that.isAllDisplayDataChecked){
            that.currentKF = 1
          }
          that.getKFList('delete')
        }
      });
    }
  }
  // table1 end

  // table2 start
  showDetail(data) {
    this.selectedKQ = data
    this.isCanAddEdit = false
    this.mapOfCheckedIdDetail = {}
    this.deleteKQList = []
    this.getKQList()
  }
  getKQList() {
    let selectedId = this.selectedKQ
    for (let i = 0; i < this.listOfAllData.length; i++) {
      if (this.listOfAllData[i].id == selectedId) {
        let newList = this.listOfAllData[i].warehouseAreas
        this.listOfAllDataDetail = newList
      }
    }
  }

  isCanAddEdit: boolean = true;
  isAllDisplayDataCheckedDetail = false;
  isOperatingDetail = false;
  isIndeterminateDetail = false;
  listOfDisplayDataDetail = [];
  listOfAllDataDetail = [];
  mapOfCheckedIdDetail: { [key: string]: boolean } = {};
  numberOfCheckedDetail = 0;
  deleteKQList = [];
  isEditKQ: boolean = false

  currentPageDataChangeDetail($event): void {
    this.listOfDisplayDataDetail = $event;
    this.refreshStatusDetail();
  }

  refreshStatusDetail(): void {
    this.isAllDisplayDataCheckedDetail = this.listOfDisplayDataDetail
      .filter(item => !item.disabled)
      .every(item => this.mapOfCheckedIdDetail[item.id]);
      if(this.listOfDisplayDataDetail.length==0){
        this.isAllDisplayDataCheckedDetail = false
      }
    this.isIndeterminateDetail =
      this.listOfDisplayDataDetail.filter(item => !item.disabled).some(item => this.mapOfCheckedIdDetail[item.id]) &&
      !this.isAllDisplayDataCheckedDetail;
    this.numberOfCheckedDetail = this.listOfAllDataDetail.filter(item => this.mapOfCheckedIdDetail[item.id]).length;
    // 删除库区id
    let newList = []
    let ids = Object.keys(this.mapOfCheckedIdDetail)
    for (let i = 0; i < ids.length; i++) {
      if (this.mapOfCheckedIdDetail[ids[i]]) {
        newList.push(ids[i])
      }
    }
    this.deleteKQList = newList
  }

  checkAllDetail(value: boolean): void {
    this.listOfDisplayDataDetail.filter(item => !item.disabled).forEach(item => (this.mapOfCheckedIdDetail[item.id] = value));
    this.refreshStatusDetail();
  }
  // 删除库区
  geleteCurkq(id: any) {
    let that = this
    that.isEditKQ = true
    this.modalService.confirm({
      nzTitle: '确定要删除此条数据吗？',
      nzContent: '',
      nzOkText: '确认',
      nzCancelText: '取消',
      nzOnOk: async function () {
        that.deleteKQList.push(id)
        let _res1: any = await that.subwarehouseManageService.deletekq(that.deleteKQList)
        that.deleteKQList = []
        that.getKFList()
      },
      nzOnCancel: function () {
        that.deleteKQList = []
      }
    });
  }
  deleteMorekq() {
    let that = this
    that.isEditKQ = true
    if (this.deleteKQList.length == 0) {
      this.message.create("error", "请选择删除条目")
    } else {
      this.modalService.confirm({
        nzTitle: '确定要删除这些数据吗？',
        nzContent: '',
        nzOkText: '确认',
        nzCancelText: '取消',
        nzOnOk: async function () {
          let _res2: any = await that.subwarehouseManageService.deletekq(that.deleteKQList)
          that.deleteKQList = []
          that.mapOfCheckedIdDetail = {}
          that.getKFList()
        }
      });
    }
  }

  // table2 end

  // KF table modal start
  kfModalId = null;
  kfModalType: number = 1;
  isVisibleKF: boolean = false;
  kfCodeModal: string = '';
  kfNameModal: string = '';
  kfAddrModal: string = '';
  isIndependent: boolean = false;
  kfTypeModal: string = '';
  clTypeModal: string = ''
  kfWareHouseAreas = [];
  KfForm: FormGroup;
  showModalKF(type): void {
    this.kfModalType = type
    this.isVisibleKF = true;
    if(type==2){
      let data = this.listOfAllData.filter(item=>{
        return item.id == this.deleteKFList[0]
      })[0]
      this.kfModalId = data.id
      this.kfWareHouseAreas = data.warehouseAreas
      this.KfForm.patchValue({
        kfCodeModal: data.code,
        kfNameModal: data.name,
        kfAddrModal: data.address,
        isIndependent: data.independent,
        kfTypeModal: data.category,
        clTypeModal: data.materialCategory
      })
    }else{
      this.KfForm.reset()
      this.kfWareHouseAreas = []
    }
  }
  handleCancelKF(): void {
    this.isVisibleKF = false;
  }
  // 新增或修改库房
  submitKF(): void {
    for (const i in this.KfForm.controls) {
      this.KfForm.controls[i].markAsDirty();
      this.KfForm.controls[i].updateValueAndValidity();
    }
    if (this.KfForm.status == "VALID") {
      let _value = this.KfForm.value;
      this.addEditKFModal(_value)
    }
  }
  async addEditKFModal(value) {
    let data1 = {
      code: value.kfCodeModal,
      address: value.kfAddrModal == null ? '' : value.kfAddrModal,
      category: value.kfTypeModal,
      independent: value.isIndependent == null ? '' : value.isIndependent,
      materialCategory: value.clTypeModal,
      name: value.kfNameModal,
      warehouseAreas: this.kfWareHouseAreas
    }
    let data2 = {
      id: this.kfModalId,
      code: value.kfCodeModal,
      address: value.kfAddrModal == null ? '' : value.kfAddrModal,
      category: value.kfTypeModal,
      independent: value.isIndependent == null ? '' : value.isIndependent,
      materialCategory: value.clTypeModal,
      name: value.kfNameModal,
      warehouseAreas: this.kfWareHouseAreas
    }
    if (this.kfModalType == 1) {
      let _res1 = await this.subwarehouseManageService.addEditKFList(data1)
    } else if (this.kfModalType == 2) {
      let _res2 = await this.subwarehouseManageService.addEditKFList(data2)
    }
    this.isVisibleKF = false;
    this.getKFList()
  }
  // KF table modal end
  // KQ table modal start
  kqModalType: number = 1;
  modalKQId: string = '';
  isVisibleKQ: boolean = false;
  kqCodeModal: string = '';
  pmCodeModal: string = '';
  lcCodeModal: string = '';
  kqNameModal: string = '';
  kqDescModal: string = '';
  kqTypeModal: string = '';
  qyModal: string = '';
  kqForm: FormGroup;
  showModalKQ(type): void {
    this.kqModalType = type
    this.isVisibleKQ = true;
    if (type == 2) {
      let data = this.listOfAllDataDetail.filter(item=>{
        return item.id == this.deleteKQList[0]
      })[0]
      this.modalKQId = data.id
      this.kqForm.patchValue({
        kqCodeModal: data.code,
        pmCodeModal: data.ink,
        lcCodeModal: data.bunker,
        kqNameModal: data.name,
        kqDescModal: data.description,
        kqTypeModal: data.category,
        qyModal: data.area
      })
    }else{
      this.kqForm.reset()
    }
  }

  handleCancelKQ(): void {
    this.isVisibleKQ = false;
  }
  //新增修改库区
  submitKQ(): void {
    for (const i in this.kqForm.controls) {
      this.kqForm.controls[i].markAsDirty();
      this.kqForm.controls[i].updateValueAndValidity();
    }
    if (this.kqForm.status == 'VALID') {
      let _value = this.kqForm.value;
      this.addEditKQ(_value)
    }
  }
  async addEditKQ(data) {
    let _data1 = {
      area: data.qyModal == null ? '' : data.qyModal,
      bunker: data.lcCodeModal,
      category: data.kqTypeModal == null ? '' : data.kqTypeModal,
      code: data.kqCodeModal,
      description: data.kqDescModal == null ? '' : data.kqDescModal,
      ink: data.pmCodeModal,
      name: data.kqNameModal,
      warehouseId: this.selectedKQ
    }
    let _data2 = {
      id: this.modalKQId,
      area: data.qyModal == null ? '' : data.qyModal,
      bunker: data.lcCodeModal,
      category: data.kqTypeModal == null ? '' : data.kqTypeModal,
      code: data.kqCodeModal,
      description: data.kqDescModal == null ? '' : data.kqDescModal,
      ink: data.pmCodeModal,
      name: data.kqNameModal,
      warehouseId: this.selectedKQ
    }
    this.isEditKQ = true
    if (this.kqModalType == 1) {
      let _res1: any = await this.subwarehouseManageService.addKQList(_data1)
    } else if (this.kqModalType == 2) {
      let _res2: any = await this.subwarehouseManageService.editKQList(_data2)
    }
    this.getKFList()
    this.isVisibleKQ = false;
  }
  // KQ table modal end

}
